<template>
    <div id='head_top' class="head_top_template">
        <div class="container">
            <div class="slot-container">
                <slot></slot>
            </div>
            <div class="logo">
                <!--logo-->
                <a class="site_logo" href="/"
                   :style="getBGImage(logoImageUrl)">
                </a>
                <!--logo-->
            </div>
            <div class="explore">
                <!--explorer-->
                <router-link to="/explore">
                    <span>Explore</span>
                    <!-- <el-popover
                       placement="bottom"
                       open-delay="200"
                       transition="collapse-transition"
                       trigger="hover">
                       <explorer-view></explorer-view>
                       <span slot="reference">Explore</span>
                     </el-popover>-->
                </router-link>
            </div>

            <div class="explore">
                <!--explorer-->
                <router-link to="/bookmark">
                    <span>Bookmarks</span>
                    <!-- <el-popover
                       placement="bottom"
                       open-delay="200"
                       transition="collapse-transition"
                       trigger="hover">
                       <explorer-view></explorer-view>
                       <span slot="reference">Explore</span>
                     </el-popover>-->
                </router-link>
            </div>

            <div class="intro">
                <!--<router-link to="/about/intro">
                  &lt;!&ndash;explorer&ndash;&gt;
                  <span> What We Do</span>
                </router-link>-->
            </div>
            <div class="search">
                <!-- <el-autocomplete
                   v-model="state4"
                   :fetch-suggestions="querySearchAsync"
                   placeholder="请输入内容"
                   @select="handleSelect"
                 >
                   <el-button slot="append" icon="el-icon-search"></el-button>
                 </el-autocomplete>-->
            </div>

        </div>

        <div class="right-container">
            <!-- <router-link to="/about/intro">
               <span>For Entrepreneurs</span>
             </router-link>-->
            <!--暂时隐藏-->
            <!--<p @click="gotoCreate">
                <span>Start a Campaign</span>
            </p>-->
            <div v-if="userLoginStatus" class="profile-container">
                <div class="icon" :style="getBGImage(avatar)"></div>
                <el-dropdown @command="handleCommand">
                <span class="el-dropdown-link">
                {{userName}}
                <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="campaign">
                            <router-link to="/campaign/list">
                                My Campaigns
                            </router-link>
                        </el-dropdown-item>
                        <el-dropdown-item command="profile">
                            <router-link to="/profile">
                                Profile
                            </router-link>
                        </el-dropdown-item>
                        <el-dropdown-item command="logout">Log Out</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
            <div v-else>
                <span class="siteHeader-divider"></span>
                <span @click="loginInHandler" style="cursor: pointer">Log In</span>
                <span @click="signUpHandler" style="cursor: pointer">Sign Up</span>
            </div>
        </div>


        <!--Login in form-->
        <el-dialog :visible.sync="dialogFormVisible">
            <el-form :model="userForm" ref="userForm" label-width="100px" class="demo-dynamic">
                <el-form-item prop="email" label="UserName" :rules="[
            { required: true, message: 'Email can not be empty', trigger: 'blur' }

          ]">
                    <el-input v-model="userForm.email"></el-input>
                </el-form-item>
                <!--<el-form-item prop="password" label="Password" :rules="[
            { required: true, message: 'Password can not be empty', trigger: 'blur' },
          ]">
                    <el-input v-model="userForm.password" type="password"></el-input>
                </el-form-item>-->
                <el-form-item>
                    <el-button type="primary" @click="loginButtonClickHandler">Confirm</el-button>
                    <el-button @click="cancelClickHandler">Cancel</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!--Sign in form-->
        <el-dialog :visible.sync="loginFormVisible">
            <el-form :model="signUserForm" ref="userForm" label-width="100px" class="demo-dynamic">

                <el-form-item style="display: none" prop="userName" label="User Name" :rules="[
            { required: true, message: 'User name can not be empty', trigger: 'blur' },
          ]">
                    <el-input v-model="signUserForm.email"></el-input>
                </el-form-item>
                <el-form-item prop="email" label="UserName" :rules="[
            { required: true, message: 'Email can not be empty', trigger: 'blur' },
            /*{ type: 'email', message: 'Email format not correct', trigger: ['blur'] }*/
          ]">
                    <el-input v-model="signUserForm.email"></el-input>
                </el-form-item>
                <!-- <el-form-item prop="password" label="Password" :rules="[
             { required: true, message: 'Password can not be empty', trigger: 'blur' }
           ]">
                     <el-input v-model="signUserForm.password" type="password"></el-input>
                 </el-form-item>-->

                <el-form-item>
                    <el-button type="primary" @click="registerButtonClickHandler">Confirm</el-button>
                    <el-button @click="cancelClickHandler">Cancel</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

    </div>
</template>

<script>
    import {mapState, mapGetters, mapActions} from 'vuex'
    import {setToken, removeToken} from '@/utils/auth'
    import {saveUserLog} from '@/api/log'

    export default {
        data() {
            return {
                restaurants: [],
                state4: '',
                timeout: null,
                dialogFormVisible: false,
                loginFormVisible: false,
                formLabelWidth: '120px',
                userForm: {
                    email: '',
                    password: "test",
                },
                signUserForm: {
                    userName: '',
                    email: '',
                    password: 'test'
                },
                logoImageUrl: 'static/img/logo.png'
            }
        },
        created() {

            console.log("login-------")
            console.log(this.userLoginStatus)
            if (!this.userLoginStatus) {
                console.log("999999")
                this.openRegistrerForm()
            }
            console.log("login-------")

        },
        computed: {
            ...mapState({
                'userName': state => state.user.name,
                'avatar': state => state.user.avatar,
                'status': state => state.user.status,
            }),
            ...mapGetters([
                'userLoginStatus',
            ]),
        },
        components: {},
        methods: {
            ...mapActions([
                'getUserInfo'
            ]),
            getRequest(key) {
                var url = location.search;
                var theRequest = new Object();
                if (url.indexOf("?") != -1) {
                    var str = url.substr(1);
                    var strs = str.split("&");
                    for (var i = 0; i < strs.length; i++) {
                        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                    }
                }
                var value = theRequest[key];
                return value;
            },
            openRegistrerForm() {

                var value = this.getRequest("SID")
                console.log("value:-------" + value, value)

                if (value && value.length > 0) {

                    var signUserForm = {
                        userName: value,
                        email: value,
                        password: 'test'
                    }

                    this.loginHandler(signUserForm)
                } else {
                    this.$message({
                        type: 'info',
                        message: 'userinfo error'
                    });
                }


            },
            openRegistrerFormBak() {
                this.$prompt('Please enter the code you received from the previous survey to start the task:', 'Notice', {
                    confirmButtonText: 'Confirm',
                    cancelButtonText: 'Cancel'
                }).then(({value}) => {

                    if (value && value.length > 0) {

                        var signUserForm = {
                            userName: value,
                            email: value,
                            password: 'test'
                        }

                        this.loginHandler(signUserForm)
                    } else {
                        this.$message({
                            type: 'info',
                            message: 'Input can not be empty'
                        });
                    }

                }).catch(() => {

                });
            },
            getBGImage(image) {
                return "background-image: url('" + image + "');"
            },
            getAvatarImage(image) {
                console.log(image)
                var showImage = image || "static/img/default.png"
                return "background-image: url('" + showImage + "');"
            },
            loginInHandler() {
                this.loginFormVisible = false
                this.dialogFormVisible = true


                // this.$emit("loginInHandler")
            },
            signUpHandler() {
                this.dialogFormVisible = false
                this.loginFormVisible = true;
                // this.$emit("signUpHandler")

            },
            // 用户注册登陆事件
            registerButtonClickHandler() {
                var that = this
                this.signUserForm.userName = this.signUserForm.email
                this.registerHandler(this.signUserForm)

            },
            registerHandler(form) {

                var that = this

                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });

                this.$store.dispatch('RegisterUser', form).then((res) => {
                    console.log(res)
                    that.loading = false
                    that.loginFormVisible = false
                    loading.close()
                    that.$router.push({
                        path: '/'
                    })
                }).catch(() => {
                    loading.close()
                })

            },
            // 用户登陆处理事件
            loginButtonClickHandler() {
                var that = this

                this.signUserForm.email = this.signUserForm.userName
                this.loginHandler(this.userForm)


            },
            loginHandler(userForm) {

                var that = this

                var tip = {
                    operation: "user login",
                    params: JSON.stringify({"userEmail": userForm.email})

                }


                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });

                console.log("1111111111111")

                this.$store.dispatch('LoginByUsername', userForm).then((res) => {
                    that.loading = false
                    that.dialogFormVisible = false
                    // 设置token
                    console.log(res)

                    var tip2 = {
                        operation: "Start_task",
                        params: JSON.stringify({
                            "user": that.userName, "time": new Date().getTime(),
                            "version": res.version
                        })

                    }
                    saveUserLog(tip2);


                    that.$router.push({
                        path: '/'
                    })
                    loading.close()
                }).catch(() => {
                    loading.close()
                })

                console.log(userForm)

            },
            cancelClickHandler() {
                this.loginFormVisible = false
                this.dialogFormVisible = false
            },
            test() {
                console.log("dd");
            },
            handleCommand(command) {
                var that = this

                var tip = {
                    operation: "user log out",
                    params: JSON.stringify({"userEmail": this.userName})

                }

                saveUserLog(tip);

                if (command == "logout") {

                    this.$store.dispatch('LogOut').then((res) => {
                        window.sessionStore.clear()
                        that.$message.success("Logout Successfully")
                        this.$router.push('/home');
                        window.location.reload()
                    }).catch(() => {
                        window.sessionStore.clear()
                        that.$message.error("Logout Failure, please refresh page and try again")
                        this.$router.push('/home');
                        window.location.reload()
                    })
                }
            },
            gotoCreate() {

                // if (this.status) {
                this.$router.push('/create');
                /* } else {
                     window.sessionStore.clear()
                     this.$router.push("/")
                     // window.location.reload()
                     this.$message.error("you need to login in first, please refresh page!")
                 }*/

            }
        },

    }

</script>

<style lang="scss" scoped>
    @import '../../style/mixin';

    .head_top_template {
        font-size: 20px;
        background-color: #ffffff;
        border-bottom: 1px solid #dddddd;
        display: flex;
        justify-content: space-between;
        span {
            font-family: "Benton Sans", "Helvetica", "sans-serif";
            font-weight: bold;
            font-size: 14px;
            line-height: 20px;
            margin-left: 30px;
        }
        .container {
            display: flex;
            height: 60px;
            padding: 0 20px;
            align-items: center;
            .slot-container {
                margin-right: 16px;
            }
            .logo {
                height: 60px;
                display: flex;
                align-items: center;
                justify-content: center;
                .site_logo {
                    height: 24px;
                    width: 160px;
                    fill: #EB1478;
                    background: no-repeat center;
                    background-size: cover;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                    text-align: center;
                    padding: 0 20px;
                    color: #2a2a2a;
                }
                span {
                    font-size: 16px;
                    line-height: 31px;
                    margin: 0 60px;
                }
            }
            .explore {
                height: 60px;
                display: flex;
                align-items: center;
            }
            .intro {
                height: 60px;
                display: flex;
                align-items: center;
            }
            .search {
                display: flex;
                align-items: center;
                margin-left: 50px;
            }
        }
        .right-container {
            display: flex;
            align-items: center;
            margin-right: 30px;
            .siteHeader-divider {
                height: 32px;
                width: 1px;
                background-color: #dddddd;
                margin-left: 30px;
            }
            .profile-container {
                display: flex;
                align-items: center;
                margin-left: 26px;
                .icon {
                    width: 32px;
                    height: 32px;
                    /*background: url('~assets/profile.png') no-repeat;*/
                    background-size: 100% 100%;
                }
            }

        }
    }

</style>
